package org.lgiavedoni.android.franq.service.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import org.lgiavedoni.android.franq.core.httpserver.HttpPageController;
import org.lgiavedoni.android.franq.core.service.Service;
import org.lgiavedoni.android.franq.service.config.ConfigService;
import org.lgiavedoni.android.franq.service.config.ConfigService.ConfigKey;
import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.util.network.NetworkUtil;

public class HTTPServerService extends Service {

	public static final HTTPServerService inst = new HTTPServerService();
	private final Map<String, HttpPageController> pages = new HashMap<String, HttpPageController>();
	private static final String IMPLEMENTATIONS_KEY = "httpServerPages";

	private ServerSocket server;

	@Override
	public String getServiceName() {
		return "httpServer";
	}

	@Override
	public String getInfo() {
		return super.getInfo() + "\n" + "http://" + NetworkUtil.getMyIp() + ":" + ConfigService.inst.getValueAsInt(ConfigKey.HTTPSERVER_PORT);
	}

	@Override
	protected void startInternal() {
		for (Object obj : getImplementations(IMPLEMENTATIONS_KEY)) {
			pages.put(((HttpPageController) obj).getPath(), (HttpPageController) obj);
		}

		try {
			server = new ServerSocket(ConfigService.inst.getValueAsInt(ConfigKey.HTTPSERVER_PORT));
			Logger.inst.info("TCPServer Waiting for client on port :" + server.getLocalPort());
		} catch (Exception e) {
			Logger.inst.error(e);
		}
	}

	@Override
	protected void stopInternal() {
		try {
			server.close();
		} catch (IOException e) {
			Logger.inst.error(e);
		}
	}

	@Override
	public void _run() {
		while (server != null && !server.isClosed()) {
			try {
				Socket connected = server.accept();
				new ProcessClienteRequest(connected).start();
			} catch (Exception e) {
				Logger.inst.warning(e.getMessage());
			}
		}
	}

	public Map<String, HttpPageController> getPages() {
		return pages;
	}

}
